package edu.notebook.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import edu.notebook.controller.utils.R;
import edu.notebook.domain.Note;
import edu.notebook.service.NoteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
@RequestMapping("/note")
public class NoteController {

    @Autowired
    private NoteService noteService;


    @GetMapping
    public R getAll(){
        return new R(true, noteService.getAll());
    }

    @PostMapping
    public R save(@RequestBody Note note) throws IOException {
        System.out.println(note);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = sdf.format(new Date());
        note.setCreateTime(formattedDate);
        note.setUsername("孙洪萍");
        return new R(noteService.saveBook(note),"标题为 “"+note.getTitle()+"” 的文章保存成功");
    }

    @DeleteMapping("/{id}")
    public R delete(@PathVariable Integer id){
        boolean flag = noteService.delete(id);
        return new R(flag,flag ? "删除成功^_^" : "数据同步失败，自动刷新-_-!");
    }

    @PutMapping
    public R update(@RequestBody Note note){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = sdf.format(new Date());
        note.setUpdateTime(formattedDate);
        return new R(noteService.update(note));
    }

    @GetMapping("/{id}")
    public R getById(@PathVariable Integer id){
        return new R(true, noteService.getById(id));
    }

    /**
     * 分页查询 显示在主页面上面获取所有数据
     * @param currentPage
     * @param pageSize
     * @param note
     * @return
     */
    @GetMapping("/{currentPage}/{pageSize}")
    public R getPage(@PathVariable int currentPage, @PathVariable int pageSize , Note note){
//        System.out.println(currentPage);
        IPage<Note> page = noteService.getPage(currentPage, pageSize,note);
        if( currentPage > page.getPages()){
//            System.out.println(page.getPages());
            page = noteService.getPage((int)page.getPages(), pageSize,note);
        }
        return new R(true, page);
    }



}
